<?php

namespace Sinofaneliu\LaravelStart\Models;

use Laravel\Passport\HasApiTokens;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function scopeSecret($query, $value = 1, $columns = '*')
    {
        if (defined('IS_ADMIN')) {
            return $query;
        }
        return $query->addSelect($columns)->selectRaw('? as secret', [$value]);
    }

    public function isSecret()
    {
        return isset($this->attributes['secret']) 
            && $this->attributes['id'] != optional(Auth::user())->id;
    }

    public function getNameAttribute()
    {
        return $this->isSecret()
            ? $this->secretName($this->attributes['name'])
            : $this->attributes['name'];
    }

    public function getEmailAttribute()
    {
        return $this->isSecret()
            ? $this->secretEmail($this->attributes['email'])
            : $this->attributes['email'];
    }

    public function getMobileAttribute()
    {   
        return $this->isSecret()
            ? $this->secretMobile($this->attributes['mobile'])
            : $this->attributes['mobile'];
    }

    public function secretName($name)
    {
        return substr($name, 0, 1).'***'.substr($name, -1);
    }

    public function secretEmail($email)
    {
        $pos = strrpos($email, '@');
        $name = substr($email, 0, $pos);
        $suffix = substr($email, $pos);
        return substr($name, 0, 1).'***'.substr($name, -1).$suffix;
    }

    public function secretMobile($mobile)
    {
         return substr($mobile, 0, 3).'***'.substr($mobile, -3);
    }

    public function findForPassport($login)
    {
        return User::orWhere('email', $login)->orWhere('mobile', $login)->first();
    }

    public function routeNotificationForEasySms($notification)
    {
        //return new PhoneNumber($this->number, $this->area_code);
        return $this->mobile;
    }

    // public function routeNotificationForWechatTemplate($notification)
    // {
    //     return optional($this->oauths()->where('provider', 'wechat')->first())->openid;
    // }

}
